﻿using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.DBFactory.Database;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace QYmall.Core.Services
{
    /// <summary>
    /// 文章类别接口实现
    /// </summary>
    public class ArticleCategoryService : BaseService, IArticleCategoryService
    {
        private readonly IUserService _userService;

        public ArticleCategoryService(IDbContextFactory contentFactory, IUserService userService) : base(contentFactory)
        {
            _userService = userService;
        }

        /// <summary>
        /// 根据父ID返回一级列表
        /// </summary>
        public async Task<IEnumerable<ArticleCategory>> QueryListAsync(int top, int parentId, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var result = _context.Set<ArticleCategory>().Where(x => x.ParentId == parentId).OrderByBatch("SortId,Id");
            if (top > 0) result = result.Take(top);//等于0显示所有数据
            return await result.ToListAsync();
        }

        /// <summary>
        /// 根据父ID返回目录树
        /// </summary>
        public async Task<IEnumerable<ArticleCategoryDto>> QueryListAsync(int parentId, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var listData = await _context.Set<ArticleCategory>().ToListAsync();
            //调用递归重新生成目录树
            List<ArticleCategoryDto> result = await GetChilds(listData, parentId);
            return result;
        }

        /// <summary>
        /// 根据条件删除数据(迭代删除)
        /// </summary>
        public async Task<bool> DeleteAsync(Expression<Func<ArticleCategory, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var listData = await _context.Set<ArticleCategory>().ToListAsync();//查询所有数据
            var cateList = await _context.Set<ArticleCategory>().Where(funcWhere).ToListAsync();
            if (cateList == null) return false;
            var cateIds = cateList.Select(c => c.Id).ToList();
            //查找关系表关删除
            var reList = await _context.Set<ArticleCategoryRelation>().Where(x => cateIds.Contains(x.CategoryId)).ToListAsync();
            _context.RemoveRange(reList);
            //迭代删除子级
            foreach (var modelt in cateList)
            {
                await DeleteChilds(listData, modelt.Id);//删除子节点
                _context.RemoveRange(modelt);//删除当前节点
            }

            return await this.SaveAsync();
        }

        #region 辅助私有方法
        /// <summary>
        /// 迭代循环删除
        /// </summary>
        private async Task DeleteChilds(IEnumerable<ArticleCategory> listData, int parentId)
        {
            if (_context == null)
            {
                throw new ResponseException("请选连接到数据库");
            }

            IEnumerable<ArticleCategory> models = listData.Where(x => x.ParentId == parentId);
            var cateIds = models.Select(x => x.Id).ToList();
            //查找关系表关删除
            var reList = await _context.Set<ArticleCategoryRelation>().Where(x => cateIds.Contains(x.CategoryId)).ToListAsync();
            _context.RemoveRange(reList);
            //迭代查找
            foreach (var modelt in models)
            {
                await DeleteChilds(listData, modelt.Id);//迭代
                _context.RemoveRange(modelt);
            }
        }

        /// <summary>
        /// 递归返回子级数，不是目录树
        /// </summary>
        /// <param name="data">主数据</param>
        /// <param name="parentId">父级</param>
        private List<ArticleCategory> GetChildList(List<ArticleCategory> listData, List<ArticleCategory> list, int parentId)
        {
            IEnumerable<ArticleCategory> models = listData.Where(x => x.ParentId == parentId).OrderByBatch("SortId");//查找并排序
            if (models != null)
            {
                foreach (var m in models)
                {
                    list.Add(m);
                    GetChildList(listData, list, m.Id);
                }
            }
            return list;
        }

        /// <summary>
        /// 迭代循环返回目录树(私有方法)
        /// </summary>
        private async Task<List<ArticleCategoryDto>> GetChilds(IEnumerable<ArticleCategory> listData, int parentId)
        {
            List<ArticleCategoryDto> listDto = new List<ArticleCategoryDto>();
            IEnumerable<ArticleCategory> models = listData.Where(x => x.ParentId == parentId).OrderByBatch("SortId");//查找并排序
            foreach (var modelt in models)
            {
                ArticleCategoryDto modelDto = new()
                {
                    Id = modelt.Id,
                    ParentId = modelt.ParentId,
                    Title = modelt.Title,
                    ImgUrl = modelt.ImgUrl,
                    Content = modelt.Content,
                    SortId = modelt.SortId,
                    Status = modelt.Status,
                    AddBy = modelt.AddBy,
                    AddTime = modelt.AddTime
                };
                modelDto.Children.AddRange(
                    await GetChilds(listData, modelt.Id)
                );
                listDto.Add(modelDto);
            }
            return listDto;
        }
        #endregion
    }
}
